/*
 * Copyright 2006 Berry Crawford
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.judo.frontcontroller;

import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.judo.frontcontroller.exceptions.InvalidMappingException;
import org.judo.frontcontroller.exceptions.URLMappingManager;

public class SimpleURLManager
{
	private static HashMap urlMaps = new HashMap();
	
	public static void load()
	{
		try
		{
			InputStream is = 
				(new URLMappingManager().getClass()).getResourceAsStream(
						"/simple_urls.xml");
			
			SAXBuilder builder = new SAXBuilder();
			Document doc = builder.build(is);
			Element root = doc.getRootElement();
			
			List mappings = root.getChildren();
			
			for (int i=0;i<mappings.size();i++)
			{
				Element mapping = (Element)mappings.get(i);
				
				String url = mapping.getAttributeValue("url_name");
				String mapTo = mapping.getAttributeValue("mapto");
				
				SimpleURLManager.map(url,mapTo);
			}
		}
		catch(Throwable e)
		{
			System.out.println("[FATAL ERROR]: could not load Simple URL mappings because: "+e);
		}
	}
	
	public static void map(String urlName,String mapToURL)
	{
		urlMaps.put(urlName,mapToURL);
	}
	
	public static String parseSimpleURL(HttpServletRequest request) throws InvalidMappingException
	{
		String forward = null;
		
		String paths[] = request.getRequestURI().split("/");
		String name = paths[paths.length-1];
		forward = (String)urlMaps.get(name);
		
		if (forward == null)
			throw new InvalidMappingException("The Simple URL: '"+request.getRequestURI()+"' does not have a defined map");
		
		return forward;
	}
	
	public static String mappings()
	{
		return urlMaps.toString();
	}
}
